﻿using Dora.Orm.Core.Logger;
using log4net;
using SqlSugar;
using System.Linq;

namespace Dora.Orm.SqlSugarCore
{
    public abstract class InstallSqlSugar
    {
       /// <summary>
       /// 
       /// </summary>
        public virtual string QueryConnectionString { get; set; }
        /// <summary>
        /// CUD连接字符串
        /// </summary>
        public virtual string ModifyConnectionString { get; set; }

        public ILog Logger { get; }

        protected InstallSqlSugar()
        {
            Logger = LogHelper.Log4NetInstance.LogFactory(typeof(InstallSqlSugar));
        }

        public SqlSugarClient CreateQueryInstence(bool isEnableLog = false, InitKeyType type = InitKeyType.SystemTable)
        {
            var sugarClient = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = QueryConnectionString,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = type,
                //IsShardSameThread = true //设为true相同线程是同一个SqlConnection
            });
#if DEBUG
            WriteSqlLog(sugarClient);
#endif
            if (isEnableLog)
                WriteSqlLog(sugarClient);

            return sugarClient;
        }

        public SqlSugarClient CreateModifyInstence(bool isEnableLog = false, InitKeyType type = InitKeyType.SystemTable)
        {
            var sugarClient = new SqlSugarClient(new ConnectionConfig
            {
                ConnectionString = ModifyConnectionString,
                DbType = DbType.MySql,
                IsAutoCloseConnection = true,
                InitKeyType = type,
                //IsShardSameThread = true //设为true相同线程是同一个SqlConnection
            });
#if DEBUG
            WriteSqlLog(sugarClient);
#endif
            if (isEnableLog)
                WriteSqlLog(sugarClient);

            return sugarClient;
        }

        private void WriteSqlLog(SqlSugarClient sugarClient)
        {
            sugarClient.Ado.IsEnableLogEvent = true;
//            sugarClient.Ado.LogEventStarting = (sql, pars) =>
//            {
//                Logger.Info($"sql:{sql}，params:{pars} ");
//#if DEBUG

//                System.Console.WriteLine($"sql:{sql}，params:{string.Join("&", pars.Select(x => x.ParameterName + "=" + x.Value))} ");
//#endif
//            };
            sugarClient.Aop.OnLogExecuting = (sql, pars) =>
            {
                Logger.Info($"sql:{sql}，params:{pars} ");
                //System.Console.WriteLine(sql);
                //System.Console.WriteLine(string.Join(",", pars?.Select(it => it.ParameterName + ":" + it.Value)));

                System.Console.WriteLine(sql + "\r\n" +
                sugarClient.Utilities.SerializeObject(pars.ToDictionary(it => it.ParameterName, it => it.Value)));
                System.Console.WriteLine();
            };
        }
    }
}
